package it.av.training.rest.exception;

import java.rmi.dgc.VMID;

/**
 * Generates a Global Unique IDentifier.
 * 
 */
public class GuidSequence {

    private final String prefix;
    private final Object syncLock = new Object();
    private long lastUsedTime = 0L;

    // singleton instance
    private static GuidSequence guidSequence = new GuidSequence();

    public static GuidSequence getInstance() {
        return guidSequence;
    }

    private GuidSequence() {
        this.prefix = new VMID().toString() + ":-";
    }

    public String nextGuid() {
        return prefix + getUniqueTime();
    }

    /**
     * Gives the current time as given by {@link System#currentTimeMillis()}. If necessary the timestamp is incremented to guarantee that each invocation returns a unique timestamp.
     * <p>
     * Multi-thread safe.
     * 
     * @return a unique timestamp
     */
    // Not private to facilitate test
    long getUniqueTime() {
        synchronized (syncLock) {
            long newTime = System.currentTimeMillis();
            if (newTime <= lastUsedTime) {
                newTime = lastUsedTime + 1;
            }
            lastUsedTime = newTime + 1;
            return newTime;
        }
    }

}
